import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/models/video_comment_model.dart';
import 'package:hinge/common/services/video_comment_service.dart';
import 'package:hinge/common/services/video_interaction_service.dart';
import 'package:video_player/video_player.dart';

part 'video_detail_store.g.dart';

class VideoDetailStore = _VideoDetailStore with _$VideoDetailStore;

abstract class _VideoDetailStore with Store {
  @observable
  VideoModel? video;

  @observable
  bool isLoading = false;

  @observable
  bool isLoadingComments = false;

  @observable
  bool isLiked = false;

  @observable
  bool isCollected = false;

  @observable
  VideoPlayerController? videoController;

  @observable
  bool isPlaying = false;

  @observable
  ObservableList<VideoCommentModel> comments =
      ObservableList<VideoCommentModel>();

  @computed
  bool get isVideoReady => videoController?.value.isInitialized ?? false;

  // 视频控制器监听器
  void _videoControllerListener() {
    if (videoController != null) {
      runInAction(() {
        isPlaying = videoController!.value.isPlaying;
      });
    }
  }

  @action
  Future<void> loadVideoData(String videoId) async {
    isLoading = true;
    try {
      final int id = int.tryParse(videoId) ?? 0;
      final videoList = VideoService.getVideoList();
      video = videoList.firstWhere(
        (v) => v.id == id,
        orElse:
            () => VideoModel(
              id: 0,
              coverUrl: 'assets/images/video_cover_default.jpg',
              description: 'Video not found',
              likeCount: 0,
              commentCount: 0,
              collectCount: 0,
              url: '',
            ),
      );

      // 加载评论数据
      await loadComments();

      // 确保评论数量与实际一致
      if (video != null && video!.id > 0) {
        // 获取真实的评论数
        final realCommentCount = comments.length;
        // 如果与模型不一致，更新视频信息
        if (video!.commentCount != realCommentCount) {
          video = VideoModel(
            id: video!.id,
            description: video!.description,
            url: video!.url,
            coverUrl: video!.coverUrl,
            collectCount: video!.collectCount,
            likeCount: video!.likeCount,
            commentCount: realCommentCount,
          );
          // 持久化更新
          await VideoService.updateVideo(video!);
        }
      }

      // 初始化用户的点赞和收藏状态
      _initUserInteractions();

      // 初始化视频控制器
      if (video != null && video!.url.isNotEmpty) {
        // debugPrint('正在初始化视频控制器: ${video!.url}');
        videoController?.dispose(); // 确保先释放旧的控制器
        videoController = VideoPlayerController.asset(video!.url);

        try {
          await videoController!.initialize();
          // debugPrint('视频初始化成功: ${video!.url}');
          // 添加监听器
          videoController!.addListener(_videoControllerListener);
          videoController!.play();
          videoController!.setLooping(true);
        } catch (e, stack) {
          debugPrint('视频初始化失败: $e');
          debugPrint('错误堆栈: $stack');
          videoController?.dispose();
          videoController = null;
        }
      }
    } catch (e) {
      debugPrint('加载视频失败: $e');
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<void> loadComments() async {
    if (video == null) return;

    isLoadingComments = true;
    try {
      // 从服务获取评论
      final commentsList = await VideoCommentService.getCommentsByVideoId(
        video!.id,
      );
      comments.clear();
      comments.addAll(commentsList);
    } catch (e) {
      debugPrint('加载评论失败: $e');
    } finally {
      isLoadingComments = false;
    }
  }

  @action
  Future<void> addComment(int userId, String content) async {
    if (video == null || content.trim().isEmpty) return;

    try {
      final newComment = await VideoCommentService.addComment(
        video!.id,
        userId,
        content,
      );
      comments.insert(0, newComment); // 添加到列表开头

      // 更新视频评论计数
      if (video != null) {
        runInAction(() {
          // 直接使用评论列表的长度作为准确的评论数
          video = VideoModel(
            id: video!.id,
            description: video!.description,
            url: video!.url,
            coverUrl: video!.coverUrl,
            collectCount: video!.collectCount,
            likeCount: video!.likeCount,
            commentCount: comments.length,
          );
        });

        // 持久化存储更新后的评论计数
        await VideoService.updateVideo(video!);
      }
    } catch (e) {
      debugPrint('添加评论失败: $e');
    }
  }

  // 初始化用户的点赞和收藏状态
  void _initUserInteractions() {
    // 从VideoInteractionService获取用户的点赞和收藏状态
    final currentUser = UserService.getCurrentUser();
    if (currentUser != null && video != null) {
      isLiked = VideoInteractionService.isVideoLiked(currentUser.id, video!.id);
      isCollected = VideoInteractionService.isVideoCollected(
        currentUser.id,
        video!.id,
      );
    } else {
      // 未登录或视频不存在，默认为false
      isLiked = false;
      isCollected = false;
    }
  }

  @action
  Future<void> toggleLike() async {
    if (video == null) return;

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null) return;

    // 切换状态
    isLiked = !isLiked;
    final newLikeCount = isLiked ? video!.likeCount + 1 : video!.likeCount - 1;

    try {
      // 更新视频点赞计数
      final updatedVideo = VideoModel(
        id: video!.id,
        description: video!.description,
        url: video!.url,
        coverUrl: video!.coverUrl,
        commentCount: video!.commentCount,
        collectCount: video!.collectCount,
        likeCount: newLikeCount,
      );

      await VideoService.updateVideo(updatedVideo);
      video = updatedVideo;

      // 保存用户点赞状态
      if (isLiked) {
        await VideoInteractionService.addLike(currentUser.id, video!.id);
      } else {
        await VideoInteractionService.removeLike(currentUser.id, video!.id);
      }
    } catch (e) {
      // 恢复原始状态
      isLiked = !isLiked;
      debugPrint('点赞失败: $e');
    }
  }

  @action
  Future<void> toggleCollect() async {
    if (video == null) return;

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null) return;

    isCollected = !isCollected;
    final newCollectCount =
        isCollected ? video!.collectCount + 1 : video!.collectCount - 1;

    try {
      // 更新视频收藏计数
      final updatedVideo = VideoModel(
        id: video!.id,
        description: video!.description,
        url: video!.url,
        coverUrl: video!.coverUrl,
        commentCount: video!.commentCount,
        likeCount: video!.likeCount,
        collectCount: newCollectCount,
      );

      await VideoService.updateVideo(updatedVideo);
      video = updatedVideo;

      // 保存用户收藏状态
      if (isCollected) {
        await VideoInteractionService.addCollect(currentUser.id, video!.id);
      } else {
        await VideoInteractionService.removeCollect(currentUser.id, video!.id);
      }
    } catch (e) {
      // 恢复原始状态
      isCollected = !isCollected;
      debugPrint('收藏失败: $e');
    }
  }

  @action
  void dispose() {
    if (videoController != null) {
      videoController!.removeListener(_videoControllerListener);
      videoController!.dispose();
      videoController = null;
    }
  }
}
